package data.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import data.model.Data;

public class FileIO {
	
	public static void write(String path, Data data){
		try {
			FileOutputStream out = new FileOutputStream (path);
			out.write(data.getData());
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
	
	public static byte[] read(String path){
		try {
			InputStream reader = new FileInputStream(new File(path));
			ArrayList<byte[]> read = new ArrayList<byte[]>();
			
			byte[] buffer = new byte[1024];
			byte[] temp;
			
			int len = 0;
			int totalLen = 0;
			
			while(len >= 0){
				len = reader.read(buffer);
				if(len >= 0){
					totalLen += len;
					temp = new byte[len];
					System.arraycopy(buffer, 0, temp, 0, len);
					read.add(temp);
				}
			}
			reader.close();
			
			byte[] data = new byte[totalLen];
			int i = 0;
			for(int b = 0; b<read.size(); b++){
				temp = read.get(b);
				for(int j = 0; j < temp.length; j++,i++)
					data[i] = temp[j];
			}
			
			return data;
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
